<template>
  <view>
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <view class="page_view">
      <view class="title_box">规章/营业资质</view>
      <view class="tabBtnList">
        <view class="weui-cells" v-for="(item, index) in tabMenuList" :key="index">
          <view class="item" @click.stop="tabMenuClick(index,-1)" :data-index="index" :data-innerindex="-1">
            <view class="item_content">{{item.title}}</view>
            <image class="right_icon" src="https://100000063-1252208446.file.myqcloud.com/images/macallan-remvp/right_icon.png"></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 注册入会一体弹窗 -->
    <register-widget ref="registerWidgetRef" location="customer" />
  </view>
</template>

<script>
  import api from '@/api/api';
  import tip from '@/utils/tip';
  import util from '@/utils/util';
  import NavBar from '../../components/common/navbar';
  import onlineService from '../../components/common/onlineService';
  import registerWidget from "@/components/register/register-widget.vue"
  import {
    SYSTEM_INFO,
    USER_INFO,
    USER_SPECICAL_INFO,
    CUSTOMER_INFO,
    MERCHANT_INFO,
    LOWER_WX_VERSION
  } from '@/utils/constant';
  export default {
    config: {
      navigationStyle: 'custom',
      navigationBarTitleText: ''
    },
    components: {
      navBar: NavBar,
      onlineService: onlineService,
      registerWidget
    },

    data() {
      return {
        isIpx: false,
        isShowCustomNavBar: true,
        nowPages: '',
        cartNum: 0,
        userAvatarUrl: '',
        userNickName: '',
        isAuthUserInfo: false,
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          title: '个人设置',
          navbarTitle: ''
        },
        canIUse: false,
        appId: '',
        openId: '',
        unionId: '',
        showMyOrder: false,
        showUserPolicy: false,
        showJoinMember: -1, // 加入会员  1：显示, 0 隐藏
        animationData: {},
        getCoupon: false,
        memberDetails: {},
        memberCoupons: [],
        memberLevelName: '',
        memberTotalAmount: '0', //消费金额
        sourceCode: '', //入会渠道
        tabMenuList: [
          // {
          //   title: '个人信息',
          //   path: '/pages/customer/registerSetting',
          //   authorizationRequired: true,
          //   iconFt:'mcl-gerenxinxi',
          //   index: 0,
          //   hasChild: false
          // },
          // {
          //   title: '收货地址',
          //   path: '/pages/customer/address',
          //   authorizationRequired: true,
          //   index: 1,
          //   hasChild: false,
          //   isCms: false,
          // },
          // {
          //   title: '发票信息',
          //   path: '/pages/xxxxx/xxxxx',
          //   authorizationRequired: true,
          //   index: 1,
          //   hasChild: false,
          //   isCms: false,
          // },
          {
            title: '爱丁顿个人信息保护政策',
            path: '/pages/utcms/utcms?uttype=protectionPolicy',
            authorizationRequired: false,
            index: 1,
            hasChild: false,
            isCms: true,
          },
          {
            title: 'THE MACALLAN麦卡伦线上精品店购物须知',
            path: '/pages/utcms/utcms?uttype=shoppingInstructions',
            authorizationRequired: false,
            index: 1,
            hasChild: false,
            isCms: true,
          },
          {
            title: '理性饮酒倡议书',
            path: '/pages/utcms/utcms?uttype=drinkingProposal',
            authorizationRequired: false,
            index: 1,
            hasChild: false,
            isCms: true,
          },
          {
            title: '营业资质',
            path: '/pages/utcms/utcms?uttype=businessQualification',
            authorizationRequired: false,
            index: 1,
            hasChild: false,
            isCms: true,
          },
          // {
          //   title: '退出账号',
          //   path: '/pages/xxxxx/xxxxx',
          //   authorizationRequired: true,
          //   index: 1,
          //   hasChild: false,
          //   isCms: false,
          // },
        ],
        background: '',
        isRegister: true, //默认不显示注册弹窗
        hasBindJustActive: false,
        hasReady: false,
        e: false
      };
    },
    mounted() {
      let uri = '';
      if (uni.getStorageSync('background') == undefined || uni.getStorageSync('background') == null || uni
        .getStorageSync('background') == '') {
        uri = "url('https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/crm/2020011519589.jpg')";
      } else {
        uri = 'url(' + uni.getStorageSync('background') + ')';
      }
      this.background = uri;
    },
    onLoad: async function(option) {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const accountInfo = uni.getAccountInfoSync()
      if (option.sourcecode != undefined && option.sourcecode != null && option.sourcecode != '') {
        uni.setStorageSync('sourceCode', option.sourcecode);
      }
      that.sourceCode = uni.getStorageSync('sourceCode');
      const systemInfo = uni.getStorageSync(SYSTEM_INFO);
      this.isIpx = getApp().globalData.isIpx;
      this.cartNum = uni.getStorageSync('cartNum');
      let pages = getCurrentPages();
      let currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
      that.appId = accountInfo.miniProgram.appId
      if (!!customerInfo.jwt) {
        that.getMemberDetail(customerInfo.jwt);
      } else {
        that.$commonFunction.commonLoginNew().then(function(res) {
          that.hasReady = true
          customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        })
      }
    },
    onShow() {
      getApp().cl_tracker.track('mini_program_view', {
        path: this.nowPages,
        pageName: '账号设置',
      })
    },
    methods: {
      registerStatus() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        this.getMemberDetail(customerInfo.jwt)
        if (this.e && this.e !== null) {
          this.tabMenuClick(this.e)
        }
        this.isRegister = true
      },
      getUserProfile: async function() {
        this.$commonFunction.commonLoginNew().then(res => {
          if (res.code == -1001) {
            this.$refs.registerWidgetRef.openJoinMemberModal()
          }else if(res.data && res.data.mobile){
            //  非大陆手机号按照非会员对待,重新入会
            const phoneNumberReg = /^1\d{10}$/;
            if(!phoneNumberReg.test(res.data.mobile)){
              this.$refs.registerWidgetRef.openJoinMemberModal()
            }
          }
        }).catch(() => {
          this.$refs.registerWidgetRef.openJoinMemberModal()
        })

      },
      tabMenuClick: async function(indey, innerIndex) {
        let that = this
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let userInfo = uni.getStorageSync(USER_INFO) || '';
        if (indey == 0 || indey == 1) {
          // let that = this;
          if (!customerInfo && (!userInfo || !!userInfo && !userInfo.nickName)) {
            that.getUserProfile();
            return false;
          } else if (!customerInfo && !!userInfo) {
            this.$refs.registerWidgetRef.openJoinMemberModal()
            return false;
          }
        }
        // let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        // let userInfo = uni.getStorageSync(USER_INFO);
        let index = indey
        // let innerindex = e.currentTarget.dataset.innerindex
        let innerindex = innerIndex
        // 点击二级菜单
        if (innerindex !== -1) {
          if (that.tabMenuList[index].mineItems[innerindex].authorizationRequired && !customerInfo.jwt) {
            if (!customerInfo && !userInfo) {
              that.e = e
              that.getUserProfile(e)
              return false
            } else if (!customerInfo && !!userInfo) {
              that.e = e
              that.$refs.registerWidgetRef.openJoinMemberModal()
              return false
            }
          }
          if (that.tabMenuList[index].mineItems[innerindex].isCms) {
            uni.vibrateShort({
              complete(res) {
                uni.navigateTo({
                  url: '/pages/util/help?identifier=' + that.tabMenuList[index].mineItems[innerindex]
                    .identifier + '&name=' + that.tabMenuList[index].mineItems[innerindex].title
                });
              }
            });
          } else {
            uni.navigateTo({
              url: that.tabMenuList[index].mineItems[innerindex].path
            });
          }
        }
        // 带有二级菜单的一级菜单
        if (that.tabMenuList[index].hasChild && innerindex == -1) {
          that.tabMenuList[index].isOpen = !that.tabMenuList[index].isOpen
        } else {
          if (that.tabMenuList[index].authorizationRequired && !customerInfo.jwt) {
            if (!customerInfo && !userInfo) {
              that.e = e
              that.getUserProfile(e)
              return false
            } else if (!customerInfo && !!userInfo) {
              that.e = e
              that.$refs.registerWidgetRef.openJoinMemberModal()
              return false
            }
          } else if (!that.tabMenuList[index].hasChild) {
            uni.navigateTo({
              url: that.tabMenuList[index].path
            });
            //账号设置模块埋点
            let clTrackPrams = {
              'c_area': that.tabMenuList[index].title
            }
            getApp().commonClTrack('c_ebmp_setup_click', clTrackPrams)
          }
        }
      },
      /**
       * 判断是否是会员
       *
       * @param jwt
       * @return {Promise<void>}
       */
      getMemberDetail: async function(jwt) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);

        const memberDetailsResult = await api.getMemberDetails({
          header: {
            jwt: customerInfo.jwt || jwt
          }
        });
        if (memberDetailsResult.code == 1000) {
          const phoneNumberReg = /^1\d{10}$/;
          if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
            // 非大陆手机号按照非会员对待,重新入会
            uni.removeStorageSync('memberDetails');
            that.showJoinMember = 1;
            that.hasReady = true;
            return;
          }
          that.memberDetails = memberDetailsResult.data;
          that.hasReady = true;
          if (that.memberDetails.isActive == 'Inactive') {
            that.showJoinMember = 1;
          } else {
            that.showJoinMember = 0;
            that.showGetCoupon = 0;
            that.memberLevelName = that.memberDetails.memberLevel ? that.memberDetails.memberLevel.levelName : '';
            if (that.showJoinMember == 0) {
              that.getTransactionAmounts(jwt);
            }
          }
        } else {
          that.showJoinMember = 1;
          that.hasReady = true;
        }
      },

      /**
       * 计算用户消费金额
       * Number.isInteger(3) // true
       * Number.isInteger(3.1) // false
       */
      getTransactionAmounts: async function(jwt) {
        let that = this;
        const transactionAmounts = await api.getTransactionAmounts({
          method: 'GET',
          header: {
            jwt: jwt
          },
          query: {
            period: 'LAST_365_DAYS'
          }
        });
        if (transactionAmounts.code == 1000) {
          var memberAmounts = transactionAmounts.data;
          if (Number(memberAmounts.orderAmount) >= 0 && Number(memberAmounts.refundAmount) >= 0) {
            let accumulated = memberAmounts.orderAmount - memberAmounts.refundAmount;
            //  let accumulated = 1009.8;
            if (Number.isInteger(accumulated)) {
              that.memberTotalAmount = accumulated;
              let amountFixed = accumulated.toFixed(2);
              var f_x = amountFixed.toString();
              var pos_decimal = f_x.split('.');
              var s_x = pos_decimal[1];
              if (s_x.length < 2) {
                s_x += '0';
              }
              that.memberTotalAmount = pos_decimal[0] + '.' + s_x;
            }
            if (accumulated <= 0) {
              that.memberTotalAmount = 0;
            }
          }
        }
      },
      justActive: async function(e) {
        let that = this
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let userInfo = uni.getStorageSync(USER_INFO);
        if (!customerInfo && !userInfo) {
          that.getUserProfile(e)
          return false
        } else if (!customerInfo && !!userInfo) {
          this.$refs.registerWidgetRef.openJoinMemberModal()
          return false
        } else {
          this.hasBindJustActive = true
          this.$refs.registerWidgetRef.openJoinMemberModal()
        }
      }
    }
  };
</script>

<style lang="less">
  .page_view{
    width: 100%;
    padding: 0 48rpx;
  }
  .title_box{
    margin-top: 40rpx;
    font-family: NotoSansSC-Medium;
    font-size: 48rpx;
    font-weight: 500;
    line-height: 64rpx;
    text-transform: uppercase;
    letter-spacing: 0px;
  }
  .tabBtnList {
    margin-top: 40rpx;
    .weui-cells {
      width: 100%;
      .item {
        height: 64rpx;
        display: flex;
        justify-content: space-between;
        padding: 48rpx 0 42rpx 0;
        border-bottom: 1rpx solid #f2f2f2;
        color: #000;
        box-sizing: content-box;
      }
    }
  }
  .item_content{
    font-family: NotoSansSC-Medium,FrankNew-Medium;
    font-size: 28rpx;
    font-weight: normal;
    line-height: 32rpx;
    color: #000000;
    line-height: 64rpx;
  }
  .right_icon{
    width: 64rpx;
    height: 64rpx;
  }
</style>
